<template>
	<div class="login">
		<div class="logo">
			<img src="https://fastly.jsdelivr.net/npm/@vant/assets/logo.png" alt="">
			<h2 style="margin:0;font-size:36px;line-height:60px;text-align:center;">{{webTitle}}</h2>
		</div>
		<van-form @submit="onSubmit">
		  <van-cell-group inset>
		    <van-field
		      v-model="user.username"
		      name="username"
		      label="用户名"
		      placeholder="用户名"
		      :rules="[{ required: true, message: '请填写用户名' }]"
		    />
		    <van-field
		      v-model="user.password"
		      type="password"
		      name="password"
		      label="密码"
		      placeholder="密码"
		      :rules="[{ required: true, message: '请填写密码' }]"
		    />
		  </van-cell-group>
		  <div style="margin: 16px;">
		    <van-button round block type="primary" native-type="submit">
		      {{!pageLoading?'登录':''}}<van-loading class="loading-bg" type="spinner" color="#303030" size="24px" v-show="pageLoading"/>
		    </van-button>
			<div class="reg">
				<div @click="toRegister">没有账号？立即注册</div>
			</div>
		  </div>
		</van-form>
	</div>
</template>

<script lang="ts" setup>
	import { showToast } from 'vant'
	import { useRouter } from "vue-router";
	import { login } from '../../api/home.js'
	import {ref,reactive,getCurrentInstance, onMounted} from 'vue'
	import {getPageTitle} from '../../utils/getPageTitle.js'
	
	const { proxy } = getCurrentInstance()
	const _this = proxy
	const webTitle = ref('')
	const user = reactive({
		username:'',
		password:''
	})
	const pageLoading = ref(false)
	const router = useRouter();
	localStorage.removeItem('user_token')
	const onSubmit = async (values) => {
  pageLoading.value = true
		await login(user).then(res=>{
			if(res.code === 200){
				showToast(res.message)
				pageLoading.value = false
				localStorage.setItem('user_token',res.data.token)
				localStorage.setItem('user',JSON.stringify(res.data))
				setTimeout(()=>{router.push('/home/index')},200)
			}
		})
	};
	webTitle.value = getPageTitle()
	const toRegister = ()=> {router.push('register')}
</script>

<style scoped>
	.logo{width: 100vw;text-align: center;margin: 10vh 0 5vh;}
	.logo img{width: 40vw;object-fit: contain;object-position: center;}
	.reg{text-align: center;margin-top: 20px;}
</style>
